package com.ibpd.henuocms.web.controller.manage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ibpd.common.FileCommon;
import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.assist.UploadFile;
import com.ibpd.henuocms.common.CompressPicUtil;
import com.ibpd.henuocms.common.FileUtil;
import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.IbpdFileFilter;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.ImageUtils;
import com.ibpd.henuocms.common.ListSortUtil;
import com.ibpd.henuocms.common.PathUtil;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.common.UploadFileEntity;
import com.ibpd.henuocms.entity.ContentEntity;
import com.ibpd.henuocms.entity.FileTypeEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.PageTemplateEntity;
import com.ibpd.henuocms.entity.StyleTemplateEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.service.content.ContentServiceImpl;
import com.ibpd.henuocms.service.content.IContentService;
import com.ibpd.henuocms.service.fileType.FileTypeServiceImpl;
import com.ibpd.henuocms.service.fileType.IFileTypeService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.pageTemplate.IPageTemplateService;
import com.ibpd.henuocms.service.pageTemplate.PageTemplateServiceImpl;
import com.ibpd.henuocms.service.styleTemplate.IStyleTemplateService;
import com.ibpd.henuocms.service.styleTemplate.StyleTemplateServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;

@Controller
public class FileSelecter extends BaseController {
	private INodeService nodeService=null;
	private IbpdLogger log=IbpdLogger.getLogger(FileSelecter.class);
	@RequestMapping("Manage/FileSelecter/index.do")
	public String index(Long siteId,Long nodeId,Long pageTemplateId,Long styleTemplateId,Long tenantId,String filter,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("siteId", siteId);
		model.addAttribute("nodeId", nodeId);
		model.addAttribute("pageTemplateId", pageTemplateId);
		model.addAttribute("styleTemplateId", styleTemplateId);
		model.addAttribute("tenantId", tenantId);
		model.addAttribute("filter", filter);
		return "manage/fileSelecter/index";
	}
	@RequestMapping("Manage/FileSelecter/fileExplore.do")
	public String fileExplore(Long siteId,Long nodeId,Long pageTemplateId,Long styleTemplateId,Long tenantId,Long fileTypeId,String filter,org.springframework.ui.Model model,HttpServletRequest request){
		Boolean existParam=false;
		System.out.println(request.getSession().getId());
		if(siteId!=null){
			existParam=true;
		}
		if(nodeId!=null){
			existParam=true;
		}
		if(pageTemplateId!=null){
			existParam=true;
		}
		if(styleTemplateId!=null){
			existParam=true;
		}
		if(tenantId!=null){
			existParam=true;
		}
		if(!existParam){//栏目ID或模板ID没有值
			model.addAttribute(ERROR_MSG,"nodeId或pageTemplateId或styleTemplateId或tenantId为null");
			return super.ERROR_PAGE;
		}
		IbpdCommon comm=new IbpdCommon();
		SubSiteEntity currentSite=null;
		ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
		if(siteId!=null){
			currentSite=siteServ.getEntityById(siteId);
			model.addAttribute("fileUploadPath",comm.getSubSiteUrlDir(siteId));	
		}else if(nodeId!=null){
			nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			NodeEntity node=nodeService.getEntityById(nodeId);
			if(node==null){
				model.addAttribute(ERROR_MSG,"没有找到nodeId为"+nodeId+"的栏目");
				return super.ERROR_PAGE;
			}
			currentSite=siteServ.getEntityById(node.getSubSiteId());
			model.addAttribute("fileUploadPath",comm.getNodeUrlDir(nodeId));			
//			model.addAttribute("fileUploadPath",SysUtil.getUploadFileBaseDir()+"/"+getNodeFileDir(node.getText()));			
		}else if(pageTemplateId!=null){
			IPageTemplateService ptServ=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
			PageTemplateEntity pt=ptServ.getEntityById(pageTemplateId);
			if(pt==null){
				model.addAttribute(ERROR_MSG,"没有找到id为"+pageTemplateId+"的模板");
				return super.ERROR_PAGE;				
			}
			currentSite=siteServ.getEntityById(pt.getSubSiteId());
//			model.addAttribute("fileUploadPath",comm.getPageTemplateRealDir(pageTemplateId).replace(File.separator, File.separator+File.separator));	
			model.addAttribute("fileUploadPath","/WEB-INF/jsp"+comm.getPageTemplateUrlDir(pageTemplateId));	
//			model.addAttribute("fileUploadPath",SysUtil.getUploadFileBaseDir()+"/template/"+pt.getTemplateFilePath());	
		}else if(styleTemplateId!=null){
			IStyleTemplateService stServ=(IStyleTemplateService) getService(StyleTemplateServiceImpl.class);
			StyleTemplateEntity st=stServ.getEntityById(styleTemplateId);
			if(st==null){
				model.addAttribute(ERROR_MSG,"没有找到id为"+styleTemplateId+"的模板");
				return super.ERROR_PAGE;				
			}
			currentSite=siteServ.getEntityById(st.getSubSiteId());
			model.addAttribute("fileUploadPath","/WEB-INF/jsp"+comm.getStyleTemplateUrlDir(styleTemplateId));	
		}else if(tenantId!=null){
			
			model.addAttribute("fileUploadPath",SysUtil.getTenantFileUploadDir(tenantId));	
		}
		if(currentSite==null){
			model.addAttribute(ERROR_MSG,"当前模式不属于任何站点");
			return super.ERROR_PAGE;	
		}
		model.addAttribute("currentSiteId",currentSite.getId());
		model.addAttribute("siteId", siteId);
		model.addAttribute("nodeId", nodeId);
		model.addAttribute("pageTemplateId",pageTemplateId);
		model.addAttribute("styleTemplateId",styleTemplateId);
		model.addAttribute("tenantId",tenantId);
		model.addAttribute("fileTypeId", fileTypeId);
		model.addAttribute("filter", filter);
		model.addAttribute("fileTypes",(nodeId!=null)?"*.jpg;*.jpeg;*.gif;*.png":"*.*");
		model.addAttribute("fileDesc",(nodeId!=null)?"网页图片类型":"模板需要的附件");
		return "manage/fileSelecter/fileExplore";
	}
	@RequestMapping("Manage/FileSelecter/delFiles.do")
	public void delFiles(String files,HttpServletResponse response) throws IOException{
		files=files.replace(super.getCurrentRequest().getContextPath(), "");
		IbpdLogger.getLogger(this.getClass()).info("====="+files);
		if(files!=null && !files.trim().equals("")){
			String[] fls=files.split(";");
			for(String f:fls){
				String fpath=super.getCurrentRequest().getRealPath(f);
				File file=new File(fpath);
				IbpdLogger.getLogger(this.getClass()).info(fpath);
				if(file.exists()){
					file.delete();
				}
			}
			super.printJsonData(response, "1");
		}else{
			super.printJsonData(response, "-1");
			return;
		}
	}
	@RequestMapping("Manage/FileSelecter/getFileList.do")
	public void getFileList(Long siteId,Long nodeId,Long pageTemplateId,Long styleTemplateId,Long tenantId,Long fileTypeId,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		Boolean existParam=false;
		if(siteId!=null){
			existParam=true;
		}
		if(nodeId!=null){
			existParam=true;
		}
		if(pageTemplateId!=null){
			existParam=true;
		}
		if(styleTemplateId!=null){
			existParam=true;
		}
		if(tenantId!=null){
			existParam=true;
		}
		if(!existParam){
			super.printMsg(resp, "-1", "-1", "栏目ID或模板ID没有值.");
			return;
		}
		IbpdCommon comm=new IbpdCommon();
		String dir="";
		String name="";
		NodeEntity node=null;
		PageTemplateEntity pt=null;
		StyleTemplateEntity st=null;
		ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
		if(siteId!=null){
			SubSiteEntity site=siteServ.getEntityById(siteId);
			if(site==null){
				super.printMsg(resp, "-2", "-1", "没有找到ID为"+siteId+"的站点.");
				return;
			}
			dir=comm.getSubSiteRealDir(siteId);
			name=site.getSiteName();
		}else if(nodeId!=null){
			nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			node=nodeService.getEntityById(nodeId);
			if(node==null){
				super.printMsg(resp, "-2", "-1", "没有找到ID为"+nodeId+"的栏目.");
				return;
			}
			siteId=node.getSubSiteId();
			dir=comm.getNodeRealDir(nodeId);
			name=node.getText();
		}else if(pageTemplateId!=null){
			IPageTemplateService ptServ=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
			pt=ptServ.getEntityById(pageTemplateId);
			if(pt==null){
				super.printMsg(resp, "-2", "-1", "没有找到ID为"+pageTemplateId+"的模板.");
				return;				
			}
			siteId=pt.getSubSiteId();
			dir=comm.getPageTemplateRealDir(pageTemplateId);
			name=pt.getTitle();
		}else if(styleTemplateId!=null){
			IStyleTemplateService stServ=(IStyleTemplateService) getService(StyleTemplateServiceImpl.class);
			st=stServ.getEntityById(styleTemplateId);
			if(st==null){
				super.printMsg(resp, "-2", "-1", "没有找到ID为"+pageTemplateId+"的模板.");
				return;				
			}
			siteId=st.getSubSiteId();
			dir=comm.getStyleTemplateRealDir(styleTemplateId);
			name=st.getTitle();
		}else if(tenantId!=null){
			siteId=-1L;
			dir=SysUtil.getTenantFileDir(tenantId);
			name="文件管理";
		}
			//这里需要 改变
			File dirFile=new File(dir);
			if(!dirFile.exists()){
				FileCommon.makeDir(dir, true);
//				dirFile.mkdir();
			}
			if(dirFile.isDirectory()){
				String[] fileExts=new String[]{};
				if(fileTypeId!=null){
					IFileTypeService fileTypeService=(IFileTypeService) ServiceProxyFactory.getServiceProxy(FileTypeServiceImpl.class);
					FileTypeEntity fType=fileTypeService.getEntityById(fileTypeId);
					if(fType!=null){
						fileExts=fType.getFileExts().split(FileTypeEntity.FILETYPEEXT_SPLITCHAR);
					}
				}
				File[] fls=dirFile.listFiles(new IbpdFileFilter(fileExts));
				SubSiteEntity curSite=null;
				if(siteId!=null || siteId!=-1L){
					curSite=siteServ.getEntityById(siteId);
				}else{
					curSite=null;
				}
				
				
				//取到文件后，还需要根据文件获取文件信息
				List<UploadFileEntity> fileList=new ArrayList<UploadFileEntity>();
				for(File f:fls){
					if(f.getName().lastIndexOf(".html")!=-1)
						continue;
					if(f.getName().lastIndexOf(".jsp")!=-1)
						continue;
					if(f.isDirectory())
						continue;
					UploadFileEntity fe=new UploadFileEntity();
					fe.setFileName(f.getName());
					Long time =f.lastModified();
				    Calendar cd = Calendar.getInstance();
				    cd.setTimeInMillis(time);
					fe.setCreateTime(cd.getTime());
					fe.setFileSize(f.length());
					if(siteId!=null){
						fe.setFilePath(req.getContextPath()+comm.getSubSiteUrlDir(siteId)+"/"+f.getName());
						fe.setUrlPath(fe.getFilePath());
					}if(nodeId!=null){
						fe.setFilePath(req.getContextPath()+comm.getNodeUrlDir(node.getId())+"/"+f.getName());
						fe.setUrlPath(fe.getFilePath());
					}else if(pageTemplateId!=null){
						if(StringUtils.isBlank(curSite.getDomainName())){
							log.error("站点没有设置域名,模版文件模块无法显示文件预览图");
						}
						fe.setFilePath(req.getContextPath()+"/WEB-INF/jsp"+comm.getPageTemplateUrlDir(pageTemplateId)+"/"+f.getName());
						fe.setUrlPath(curSite.getDomainName()+"/"+comm.getPageTemplateUrlDir(pageTemplateId)+"/"+f.getName());
					}else if(styleTemplateId!=null){
						if(StringUtils.isBlank(curSite.getDomainName())){
							log.error("站点没有设置域名,模版文件模块无法显示文件预览图");
						}
						fe.setFilePath(req.getContextPath()+"/WEB-INF/jsp"+comm.getStyleTemplateUrlDir(styleTemplateId)+"/"+f.getName());
						fe.setUrlPath(curSite.getDomainName()+"/"+comm.getStyleTemplateUrlDir(styleTemplateId)+"/"+f.getName());
					}else if(tenantId!=null){
						fe.setFilePath(req.getContextPath()+"/"+SysUtil.getTenantFileUploadDir(tenantId)+"/"+f.getName());
						fe.setUrlPath(fe.getFilePath());
					}
					fileList.add(fe);
				}
				ListSortUtil s=new ListSortUtil();
				s.sort(fileList, "fileName", "asc");
				
					//json
				JSONArray json=JSONArray.fromObject( fileList );
				super.printJsonData(resp, json.toString());
			}else{
				super.printMsg(resp, "-3", "-1", "当前目录不是文件夹.");
			}
			
	}

	@RequestMapping("Manage/FileSelecter/doUpload.do")
	public void doUpload(Long currentSiteId,String fileUploadDir,HttpServletRequest request,HttpServletResponse response) throws IOException{
		IbpdLogger.getLogger(this.getClass()).info(fileUploadDir);
		
		SubSiteEntity currentSite=null; 
		if(currentSiteId==null || currentSiteId<=0L){
			super.printParamErrorMsg(response);
			return;
		}
		ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
		currentSite=siteServ.getEntityById(currentSiteId);
		if(currentSite==null){
			super.printMsg(response, "-2", "-2","未找到站点");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		String basePath = request.getRealPath(fileUploadDir);
		File fbasePath = new File(basePath);
		if(!fbasePath.exists())
			fbasePath.mkdirs();
			factory.setRepository(fbasePath);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置单个文件的最大上传值
			upload.setFileSizeMax(1024*1024*100);
			// 设置整个request的最大值
			upload.setSizeMax(1024*1024*100*20);
			upload.setHeaderEncoding("UTF-8");
			
			try {
				List<?> items = upload.parseRequest(request);
				FileItem item = null;
				String fileName = null;
				String newFileName="";
			for (int i = 0 ;i < items.size(); i++){
					item = (FileItem) items.get(i);
					newFileName=getNewName(item.getName());
					fileName = basePath + File.separator +newFileName;
					if (!item.isFormField() && item.getName().length() > 0){
						item.write(new File(fileName));
						pressImage(fileName);
						uploadFileToFtpServer(currentSite,fileName);
					}
				}
				super.printMsg(response, "0", "-1",fileUploadDir+"/"+newFileName);
				return;
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	private void pressImage(String fileName) throws IllegalAccessException{
		if(StringUtils.isBlank(fileName))
			return;
		File f=new File(fileName);
		if(!f.exists()){
			IbpdLogger.getLogger(FileSelecter.class).error(fileName+"文件不存在");
			return;
		}
		if(f.isDirectory()){
			IbpdLogger.getLogger(FileSelecter.class).error(fileName+"是目录");
			return;
		}
		String enabZipPic=IbpdCommon.getInterface().getPropertiesValue("enable_zip_image");
		enabZipPic=(StringUtils.isBlank(enabZipPic)?"false":enabZipPic);
		if(checkBooleanValue(enabZipPic)){
			CompressPicUtil mypic = new CompressPicUtil(); 
	   	 	Long fileLength=mypic.getPicSize(fileName);
	   	 	double width=mypic.getPicWidth(fileName);
	   	 	double height=mypic.getPicHeight(fileName);
	        IbpdLogger.getLogger(FileSelecter.class).info("输入的图片大小：" + fileLength + "KB"); 
	        IbpdLogger.getLogger(FileSelecter.class).info("输入的图片宽度：" + width + "px"); 
	        IbpdLogger.getLogger(FileSelecter.class).info("输入的图片高度：" + height + "px"); 
	        double maxWidth=1024;
	        double maxHeight=768;
	        Long maxFileLength=(1024l*1024l*2024l);
	        Integer outputWidth=800;
	        Integer outputHeight=600;
	        if(width>maxWidth || height >maxHeight || fileLength>maxFileLength)
	        	mypic.compressPic(fileName, fileName, "", "", outputWidth, outputHeight, true); 
		}
		String enabScale=IbpdCommon.getInterface().getPropertiesValue("enable_scale_image");
		enabScale=(StringUtils.isBlank(enabScale)?"false":enabScale);
		if(checkBooleanValue(enabScale)){
			String scaleImagePath=IbpdCommon.getInterface().getPropertiesValue("scale_image_path");
			if(StringUtils.isBlank(scaleImagePath))
				return;
			PathUtil p = new PathUtil();
			scaleImagePath=p.getWebRoot()+scaleImagePath.replace("/", File.separator);
			IbpdLogger.getLogger(FileSelecter.class).info("path="+scaleImagePath);
			
			String enabLeftTop=IbpdCommon.getInterface().getPropertiesValue("scale_image_position_leftTop");
			String enabRightTop=IbpdCommon.getInterface().getPropertiesValue("scale_image_position_rightTop");
			String enabLeftBottom=IbpdCommon.getInterface().getPropertiesValue("scale_image_position_leftBottom");
			String enabRightBottom=IbpdCommon.getInterface().getPropertiesValue("scale_image_position_rightBottom");
			String enabCenter=IbpdCommon.getInterface().getPropertiesValue("scale_image_position_center");
			if(checkBooleanValue(enabLeftTop)){
				ImageUtils u=new ImageUtils(ImageUtils.LeftTop);
				u.pressImage(scaleImagePath,fileName);
			}
			if(checkBooleanValue(enabRightTop)){
				ImageUtils u=new ImageUtils(ImageUtils.RightTop);
				u.pressImage(scaleImagePath,fileName);
			}
			if(checkBooleanValue(enabLeftBottom)){
				ImageUtils u=new ImageUtils(ImageUtils.LeftBottom);
				u.pressImage(scaleImagePath,fileName);
			}
			if(checkBooleanValue(enabRightBottom)){
				ImageUtils u=new ImageUtils(ImageUtils.RightBottom);
				u.pressImage(scaleImagePath,fileName);
			}
			if(checkBooleanValue(enabCenter)){
				ImageUtils u=new ImageUtils(ImageUtils.Center);
				u.pressImage(scaleImagePath,fileName);
			}
		}
		
	}
	private Boolean checkBooleanValue(String v){
		if(StringUtils.isBlank(v)){
			return false;
		}
		if(v.toLowerCase().trim().equals("true") || v.toLowerCase().trim().equals("yes") || v.toLowerCase().trim().equals("y") || v.toLowerCase().trim().equals("1")){
			return true;
		}
		return false;
	}
	@RequestMapping(value = "doCkUpload.do")
    @ResponseBody
    public String processImageUpload(String type,Long nodeId,Long contentId,UploadFile file,HttpServletRequest request) {
		if(StringUtils.isBlank(type)){
			return "failure";
		}
		if(nodeId==null && contentId==null){
			return "failure";
		}
		SubSiteEntity currentSite=null;
		String uploadPath=request.getRealPath("/uploadFiles/");
		if(nodeId!=null){
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			NodeEntity node=nodeServ.getEntityById(nodeId);
			if(node!=null){
				uploadPath=IbpdCommon.getInterface().getNodeRealDir(nodeId);
				ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
				currentSite=siteServ.getEntityById(node.getSubSiteId());
			}
		}else if(contentId!=null){
			IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
			ContentEntity cont=contServ.getEntityById(contentId);
			if(cont!=null){
				nodeId=cont.getNodeId();
				uploadPath=IbpdCommon.getInterface().getNodeRealDir(nodeId);
				ISubSiteService siteServ=(ISubSiteService) getService(SubSiteServiceImpl.class);
				currentSite=siteServ.getEntityById(cont.getSubSiteId());
			}
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(10240000);
		// 设置临时文件存储位置
		
		String basePath = uploadPath;
		File fbasePath = new File(basePath);
		if(!fbasePath.exists())
			fbasePath.mkdirs();
			factory.setRepository(fbasePath);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置单个文件的最大上传值
			upload.setFileSizeMax(1024*1024*100);
			// 设置整个request的最大值
			upload.setSizeMax(1024*1024*100*20);
			upload.setHeaderEncoding("UTF-8");
			
			try {
				List<?> items = upload.parseRequest(request);
				FileItem item = null;
				String fileName = null;
					item = (FileItem) items.get(0);
					String newFileName=getNewName(item.getName());
//					String urlPath=request.getContextPath()+"/uploadFiles/"+newFileName;
					String urlPath=request.getContextPath()+"/"+IbpdCommon.getInterface().getNodeUrlDir(nodeId)+"/"+newFileName;;
					fileName = basePath + File.separator + newFileName;
					if (!item.isFormField() && item.getName().length() > 0){
						item.write(new File(fileName));
						pressImage(fileName);
						uploadFileToFtpServer(currentSite,fileName);
					}
					String callback=request.getParameter("CKEditorFuncNum");
		            if(StringUtils.isNotBlank(callback)){
//		            	IbpdLogger.getLogger(FileSelecter.class).info(file.getUpload().getOriginalFilename());
		                return "<script type='text/javascript'>"
		                + "window.parent.CKEDITOR.tools.callFunction(" + callback
		                + ",'" + urlPath + "',''" + ")"+"</script>";
		            }else{
//		                return "{" + file.getUpload().getOriginalFilename() + "}!Success!";
		            	IbpdLogger.getLogger(FileSelecter.class).info(file.getUpload().getOriginalFilename());
		                return "{" + urlPath + "}!Success!";
		            }
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "failure";
	}
	private void uploadFileToFtpServer(SubSiteEntity site,String fileName){
		File f=new File(fileName);
		if(f.exists()){ 
			String sitePath=FileUtil.getWebRootDirPath()+File.separator+"sites";
			String uploadPath=FileUtil.getWebRootDirPath()+File.separator+"uploadFiles";
			String templatePath=FileUtil.getWebRootDirPath()+File.separator+"WEB-INF"+File.separator+"jsp"+File.separator+"template";
			String serverPath="";
			if(fileName.toLowerCase().indexOf(sitePath.toLowerCase())!=-1){ 
				serverPath=f.getParentFile().getAbsolutePath().toLowerCase().replace(sitePath.toLowerCase(),"");		
				serverPath=serverPath.replace(File.separator, "/").substring(1);
				String[] sb=serverPath.split("/");
				serverPath="";
				for(Integer i=sb.length-1;i>=1;i--){
					serverPath="/"+sb[i]+serverPath; 
				}  
			}else if(fileName.toLowerCase().indexOf(uploadPath.toLowerCase())!=-1){ 
				serverPath="/uploadFiles";				
			}else if(fileName.toLowerCase().indexOf(templatePath.toLowerCase())!=-1){
				serverPath="/template"+new File(fileName).getParentFile().getAbsolutePath().toLowerCase().replace(templatePath.toLowerCase(),"").replace(File.separator, "/");												
			}else{ 
				 
			} 
			System.out.println("fileUpload serverPath:"+serverPath);
			super.uploadBinaryFileToServer(site,fileName, serverPath);
			return; 
		}  
	}
	private String getNewName(String fName){ 
		if(StringUtils.isBlank(fName)){
			return "";
		}
		String rtn=IbpdCommon.getInterface().getPropertiesValue("uploadFile_fileName_rename");
		rtn=(rtn==null)?"false":rtn;
		if(rtn.trim().toLowerCase().equals("true")){
			String ext=fName.substring(fName.lastIndexOf("."));
			String ff = UUID.randomUUID().toString()+ext;
			return ff;	
		}else{
			return fName;
		}
	}

}
